import type { Chart } from 'chart.js'
import ChartJS from 'chart.js/auto'

// 存储图表实例的引用
let chartInstances: {
  categoryChart: Chart | null
  articleChart: Chart | null
} = {
  categoryChart: null,
  articleChart: null
}

// 初始化图表
export function initCharts() {
  destroyCharts() // 先清理旧实例
  
  // 分类统计图表
  const categoryCtx = document.getElementById('category-chart') as HTMLCanvasElement
  chartInstances.categoryChart = new ChartJS(categoryCtx, {
    type: 'bar',
    data: { labels: [], datasets: [{}] },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: { y: { beginAtZero: true } }
    }
  })

  // 文章分布图表
  const articleCtx = document.getElementById('article-chart') as HTMLCanvasElement
  chartInstances.articleChart = new ChartJS(articleCtx, {
    type: 'doughnut',
    data: { labels: [], datasets: [{}] },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      cutout: '70%'
    }
  })

  return chartInstances
}

// 更新图表数据
export function updateCharts(
  categoryChart: Chart,
  articleChart: Chart,
  data: Category[]
) {
  try {
    // 使用Chart.js的API更新数据
    categoryChart.data.labels = data.map(d => d.name)
    categoryChart.data.datasets[0].data = data.map(d => d.articleCount)
    categoryChart.update('none') // 禁用动画

    articleChart.data.labels = data.map(d => d.name)
    articleChart.data.datasets[0].data = data.map(d => d.articleCount)
    articleChart.update('none')
  } catch (error) {
    console.error('图表更新失败:', error)
    throw error
  }
}

// 销毁所有图表
export function destroyCharts() {
  if (chartInstances.categoryChart) {
    chartInstances.categoryChart.destroy()
    chartInstances.categoryChart = null
  }
  if (chartInstances.articleChart) {
    chartInstances.articleChart.destroy()
    chartInstances.articleChart = null
  }
}